package com.xnchat.pro.thread;

import com.xnchat.pro.job.impl.ClockJob;
import org.springframework.scheduling.concurrent.CustomizableThreadFactory;

import java.util.concurrent.*;

/**
 * 维护线程关系。是否添加name由上层控制
 * @author 小凝
 */
public class ClockExecuter {
    private static final ThreadPoolExecutor es = new ThreadPoolExecutor(4, 50, 30,
            TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new CustomizableThreadFactory("xn-clock-"));
    private static ConcurrentMap<Integer, ClockJob> jobThreadRepository = new ConcurrentHashMap<>();

    public static ClockJob removeThread(int jobId, String message) {
        ClockJob clockJob = jobThreadRepository.remove(jobId);
        clockJob.toStop(message);
        clockJob.interrupt();
        return clockJob;
    }

    public static ClockJob loadJobThread(int jobId) {
        ClockJob jobThread = jobThreadRepository.get(jobId);
        return jobThread;
    }

    /**
     * @param name
     * @param time
     * @param session
     * @param id
     * @return
     */
    public static ClockJob registJobThread(String name, int time, String session, int id) {
        ClockJob clockJob = jobThreadRepository.get(id);
        if (clockJob == null) {
            clockJob = new ClockJob(name, time, session, id);
            es.submit(clockJob);
        }else {
            clockJob.addJob(name, time, session);
        }
        return jobThreadRepository.put(id, clockJob);
    }
}
